package com.yjc.hire.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class JsonUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转为字符串
     * @param obj
     * @return
     */
    public static String objectToJson(Object obj){
        try{
            String string = MAPPER.writeValueAsString(obj);
            return string;
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json转化为字符串
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T jsonToObject(String json, Class<T> clazz){
        try {
            T t = MAPPER.readValue(json, clazz);
            return t;
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> jsonToList(String json, Class<T> clazz){
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, clazz);
        try {
            List<T> list = MAPPER.readValue(json,javaType);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }
}
